<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="16"> <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <el-table
        :data="userlist"
        border
        stripe
        style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- 获取对应数据 -->
            <el-switch v-model="scope.row.mg_state" @change="usersdatachanged(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="usersDeleted(scope.row.id)"></el-button>
            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose">
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose">
      <!-- 内容主题区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      >
      <!-- 内容主题区域 -->
      <div>
        <div class="roleDialogDiv">
          当前的用户：<span v-text="userInfo.userText"></span>
        </div>
        <div class="roleDialogDiv">
          当前的角色：<span v-text="userInfo.nameText"></span>
        </div>
        <div class="roleDialogDiv">
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证电话的规则
    // var checkMobile = (rule, value, callback) => {
    //   const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
    //   if (regMobile.test(value)) {
    //     return callback()
    //   }
    //   callback(new Error('请输入合法的手机号'))
    // }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [],
      total: 0,
      currentPage: 1,
      addDialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      // 添加用户的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      selectedRoleId: '',
      userInfo: {
        id: '',
        userText: '',
        nameText: ''
      },
      // 所有角色的数据列表
      roleList: [],
      // 添加表单的规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在6~15个字符之间', trigger: 'blur' }
        ],
        // 验证邮箱
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
          // { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改表单的规则对象
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3~10个字符之间', trigger: 'blur' }
        ],
        // 验证邮箱
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
          // { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(this.userlist)
    },
    handleSizeChange(val) {
      // 条数
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // 当前页数
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async usersdatachanged(userinfo) {
      // 监听开关状态
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    addUser() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) {
        } else {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error('添加用户失败!!')
          }
          this.$message.success('添加用户成功!!')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    addDialogClose() {
      // 监听用户对话框的关闭时间
      this.$refs.addForm.resetFields()
    },
    showEditDialog(data) {
      this.editDialogVisible = true
      this.editForm.username = data.username
      this.editForm.email = data.email
      this.editForm.mobile = data.mobile
      this.editForm.id = data.id
    },
    editDialogClose() {
      // 监听用户对话框的关闭时间
      this.$refs.editForm.resetFields()
    },
    editUser() {
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          console.log(valid)
        } else {
          const { data: res } = await this.$http.put(`users/${this.selectedRoleId}`, this.editForm)
          if (res.meta.status !== 200) return this.$message.error('修改失败')
          this.$message.success(res.meta.msg)
          this.getUserList()
          this.editDialogVisible = false
        }
      })
    },
    usersDeleted(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async setRole(userinfo) {
      this.userInfo.id = userinfo.id
      this.userInfo.userText = userinfo.username
      this.userInfo.nameText = userinfo.role_name
      this.roleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('\n' + '获取失败 !')
      }
      this.roleList = res.data
    },
    // 分配权限
    async saveRoleInfo() {
      if (this.selectedRoleId) {
        const { data: res } = await this.$http.put(`users/${parseInt(this.userInfo.id)}/role`, { rid: this.selectedRoleId })
        this.selectedRoleId = ''
        this.roleDialogVisible = false
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
      } else {
        this.$message.warning('\n' + '请选择要分配的角色！')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination{
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.roleDialogDiv{
  margin-bottom: 22px;
}
.roleDialogDiv:last-child{
  margin-bottom: 0;
}
</style>
